package com.quectel.cms.controller.entranceguard;


import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.device.entranceguard.BindDeviceVo;
import com.quectel.cms.vo.device.entranceguard.VillageTreeVo;
import com.quectel.constant.core.device.DeviceCategoryCodeConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceCategoryService;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.dto.VillageFloorDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageFloorService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-15 14:29:44
 */
@RestController
@RequestMapping("entranceGuardDevice")
@Tag(name = "EntranceGuardDeviceController", description = "门禁设备管理相关api")
public class EntranceGuardDeviceController extends BaseController {

    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private DeviceCategoryService deviceCategoryService;

    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageFloorService villageFloorService;
    @DubboReference
    private VillageRoomService villageRoomService;

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "entranceGuardDevice:list")
    @Operation(summary = "门禁设备管理的分页查询列表")
    public Response<Page<DeviceDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest)).like("name");

        super.fillAuthorityData(request.getParams());

        request.put("deviceCategoryId", String.valueOf(deviceCategoryService.selectCacheByCode(DeviceCategoryCodeConstants.INTELLIGENT_ENTRANCE_GUARD).getId()));

        int total = deviceService.queryTotal(request.getParams());

        List<DeviceDto> list = null;
        if (total > 0) {
            list = deviceService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<DeviceDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<DeviceDto>>ok().wrap(page);
    }

    @GetMapping("treeList")
    @RequirePermissions(values = "entranceGuardDevice:list")
    @Operation(summary = "查询树形的门禁设备管理列表")
    public Response<List<VillageTreeVo>> treeList(@RequestParam Map<String, Object> params) {
        List<VillageTreeVo> list = new ArrayList<>();

        if (params.containsKey("villageId") && StringUtils.isNotBlank((String) params.get("villageId"))) {
            Long villageId = Long.valueOf((String) params.get("villageId"));
            List<VillageBuildingDto> buildingDtos = villageBuildingService.selectByVillageId(villageId);
            for (VillageBuildingDto buildingDto : buildingDtos) {
                VillageTreeVo villageTreeVo = new VillageTreeVo();
                villageTreeVo.setId(buildingDto.getId());
                villageTreeVo.setName(buildingDto.getName());
                villageTreeVo.setLevel((byte) 2);
                villageTreeVo.setParentId(villageId);
                list.add(villageTreeVo);
            }
        } else if (params.containsKey("buildingId") && StringUtils.isNotBlank((String) params.get("buildingId"))) {
            Long buildingId = Long.valueOf((String) params.get("buildingId"));
            List<VillageFloorDto> floorDtos = villageFloorService.selectByBuildingId(buildingId);
            for (VillageFloorDto floorDto : floorDtos) {
                VillageTreeVo villageTreeVo = new VillageTreeVo();
                villageTreeVo.setId(floorDto.getId());
                villageTreeVo.setName(floorDto.getName());
                villageTreeVo.setLevel((byte) 3);
                villageTreeVo.setParentId(buildingId);
                list.add(villageTreeVo);
            }

        } else if (params.containsKey("floorId") && StringUtils.isNotBlank((String) params.get("floorId"))) {
            Long floorId = Long.valueOf((String) params.get("floorId"));
            List<VillageRoomDto> roomDtos = villageRoomService.selectByFloorId(floorId);
            for (VillageRoomDto roomDto : roomDtos) {
                VillageTreeVo villageTreeVo = new VillageTreeVo();
                villageTreeVo.setId(roomDto.getId());
                villageTreeVo.setName(roomDto.getName());
                villageTreeVo.setLevel((byte) 4);
                villageTreeVo.setParentId(floorId);
                list.add(villageTreeVo);
            }

        } else {
            super.fillAuthorityData(params);
            VillageTreeVo root = new VillageTreeVo();
            root.setId(0L);
            root.setParentId(-1L);
            root.setLevel((byte) 0);
            root.setName("全部小区");
            list.add(root);
            List<VillageDto> villages = villageService.queryList(params);
            for (VillageDto village : villages) {
                VillageTreeVo villageTreeVo = new VillageTreeVo();
                villageTreeVo.setId(village.getId());
                villageTreeVo.setName(village.getName());
                villageTreeVo.setLevel((byte) 1);
                villageTreeVo.setParentId(0L);
                list.add(villageTreeVo);
            }

        }
        return Response.<List<VillageTreeVo>>ok().wrap(list);
    }

    /**
     * 修改
     */
    @PostMapping("signInstallStatus")
    @RequirePermissions(values = "entranceGuardDevice:signInstallStatus")
    @Operation(summary = "标记设备状态")
    @Log(express = "标记设备状态")
    public Response<Object> signInstallStatus(@RequestBody DeviceDto deviceDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(deviceDto.getId()));
        if (deviceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(deviceDto);

        deviceDto.setInstallTime(new Date());
        deviceService.updateById(deviceDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("bind")
    @RequirePermissions(values = "entranceGuardDevice:bind")
    @Operation(summary = "绑定门禁能力和门禁设备")
    public Response<Object> bind(@RequestBody BindDeviceVo bindDeviceVo) {
        int successCount = 0;
        List<DeviceDto> deviceDtoList = bindDeviceVo.getDeviceDtoList();
        if (deviceDtoList != null && deviceDtoList.size() > 0) {
            for (DeviceDto deviceDto : deviceDtoList) {
                if (!Objects.equals(deviceDto.getDeviceCategoryId(), deviceCategoryService.selectCacheByCode(DeviceCategoryCodeConstants.INTELLIGENT_ENTRANCE_GUARD).getId())) {
                    continue;
                }
                successCount++;

                DeviceDto updateObj = deviceService.selectById(deviceDto.getId());

                if (bindDeviceVo.getVillageTreeVo().getLevel().intValue() == 1) {
                    //小区
                    updateObj.setVillageId(bindDeviceVo.getVillageTreeVo().getId());
                    updateObj.setBuildingId(null);
                    updateObj.setFloorId(null);
                    updateObj.setRoomId(null);
                } else if (bindDeviceVo.getVillageTreeVo().getLevel().intValue() == 2) {
                    updateObj.setVillageId(bindDeviceVo.getVillageTreeVo().getParentId());
                    updateObj.setBuildingId(bindDeviceVo.getVillageTreeVo().getId());
                    updateObj.setFloorId(null);
                    updateObj.setRoomId(null);
                } else if (bindDeviceVo.getVillageTreeVo().getLevel().intValue() == 3) {
                    VillageFloorDto villageFloorDto = villageFloorService.selectById(bindDeviceVo.getVillageTreeVo().getId());
                    if (villageFloorDto != null) {
                        updateObj.setVillageId(villageFloorDto.getVillageId());
                        updateObj.setBuildingId(villageFloorDto.getBuildingId());
                        updateObj.setFloorId(villageFloorDto.getId());
                    }
                    updateObj.setRoomId(null);
                } else if (bindDeviceVo.getVillageTreeVo().getLevel().intValue() == 4) {
                    VillageRoomDto roomDto = villageRoomService.selectById(bindDeviceVo.getVillageTreeVo().getId());
                    if (roomDto != null) {
                        updateObj.setVillageId(roomDto.getVillageId());
                        updateObj.setBuildingId(roomDto.getBuildingId());
                        updateObj.setFloorId(roomDto.getFloorId());
                        updateObj.setRoomId(roomDto.getId());
                    }
                }
                deviceService.updateAllColumnById(updateObj);
            }
        }

        return Response.ok().wrap("关联设备成功数为:" + successCount + (successCount < bindDeviceVo.getDeviceDtoList().size() ? ",未关联成功不属于智慧门禁设备种类" : ""));
    }

}
